//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');

Page({
  data: {
    hideShopPopup: true,
    goodsDetail: '',//商品详情
    spec:'',//规格
    spec_category:'',//规格类别
    buyNumber:1,
    resourceUrl: app.globalData.apiUrl + '/public/uploads/goods/',
    shopNum:0,//购物车数
    price:0,
    status:false,
    //海报
    maskHidden: false,
    name: "产品名称",
    price1: "￥123",
    
  },

  
  onLoad: function (e) {
    var that = this;
    var goods_id = e.id;//商品id
    //购物车数量
    that.cartShopNum()
    /**
     * 查询商品详情
     */
    wx.request({
      url: app.globalData.apiUrl+'/api/goods/goodsInfo',
      data: {id:goods_id},
      method: 'GET',
      dataType: 'json',
      success: function(res) {
        that.setData({ goodsDetail:res.data})
        //富文本
        WxParse.wxParse('content', 'html', res.data.content, that, 0);
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    /**
     * 商品规格类别
     * 
     */
    wx.request({
      url: app.globalData.apiUrl + '/api/goods/spec_category',
      method: 'GET',
      dataType: 'json',
      success: function(res) {
        that.setData({ spec_category:res.data})
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    /**
     * 该商品的规格
     */
    wx.request({
      url: app.globalData.apiUrl + '/api/goods/goodsSpec',
      data: {id:goods_id},
      method: 'GET',
      dataType: 'json',
      success: function(res) {
        console.log(res.data)
        that.setData({spec:res.data})
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    
  },
  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/cart/cart"
    });
  },
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  /**
   * 立即购买
   */
  tobuy: function () {
    
      this.setData({
        shopType: "tobuy"
      });

      this.bindGuiGeTap();
   
    
    
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function () {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  /**
   * 选择数量(减)
   */
  numJianTap: function () {
    if (this.data.buyNumber > 1) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  /**
   * 选择数量(加)
   */
  numJiaTap: function () {
    if (this.data.buyNumber < 10) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  /**
   * 默认选择规格
   * @param {Object} e
   */
  labelItemTap: function (e) {
     var that = this
     var spec = that.data.spec
     for(var i in spec){
       if(spec[i].active !=1){
         return true;
       }
     }
  },
  /**
  * 加入购物车
  */
  addShopCar: function () {
    var that = this
    if (this.data.goodsDetail.properties && !this.data.canSubmit) {
      if (!this.data.canSubmit) {
        wx.showModal({
          title: '提示',
          content: '请选择商品规格！',
          showCancel: false
        })
      }
      this.bindGuiGeTap();
      return;
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }
    //组建购物车
    var shopCarInfo = this.bulidShopCarInfo();
    // 写入本地存储
    wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })
    this.setData({
      shopCarInfo: shopCarInfo,
     
    });

    
    this.closePopupTap();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000,
      complete: function(){
        that.cartShopNum()//购物车数量
      }
    })
    
  },
	/**
	  * 立即购买
	  */
  buyNow: function () {
    
   
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return ;
    }
    this.bindGuiGeTap();
   
    //组建立即购买信息
    var buyNowInfo = this.buliduBuyNowInfo();
    // 写入本地存储
    wx.setStorage({
      key: "buyNowInfo",
      data: buyNowInfo
    })
    this.closePopupTap();
    console.log(1111111)
    wx.navigateTo({
      url: "/pages/zhifu/zhifu?orderType=buyNow"
    })
    
  },
  /**
   * 组建商品到购物车
   */
  bulidShopCarInfo:function (){
    var that = this
    var id = this.data.goodsDetail.id//商品id
    var goods_name = this.data.goodsDetail.title//商品名称
    var goods_image = this.data.goodsDetail.image //图片
    var num = this.data.buyNumber//购买数量
    var price = this.data.price==0 ? this.data.goodsDetail.price : this.data.price//单价(计算了规格)
    var spec = this.data.spec//规格
    var label = '';
    for (var i in spec) {
      if (spec[i].active == 1) {
        label += '"' + spec[i].spec_name + '"' + ','
      }
    }
    
    var shopCarInfo = wx.getStorageSync("shopCarInfo")
    console.log(shopCarInfo)
    if (!shopCarInfo){
      var arr ={goodsList:[],totalPrice:0}
      console.log(arr)
      arr.goodsList=[{'id':id, 'goods_name': goods_name, 'goods_image': goods_image, 'num': num, 'price': price, 'active':true,'label':label}]
      console.log('第一次添加到购物车')
    }else{
      console.log('第二次添加到购物车')
      var arr = shopCarInfo;
      var strId = ''
      var strPrice = ''
      for(var i in arr.goodsList){
        
        if(arr.goodsList[i].id==id && arr.goodsList[i].price == price){
          arr.goodsList[i].num=arr.goodsList[i].num+num;
          // arr.goodsList[i].price = arr.goodsList[i].price + price;
          
        } 
        strId += arr.goodsList[i].id+',';
        strPrice +=arr.goodsList[i].price+',';
      }
      
     
      // console.log(strId)
      if (strId.indexOf(id) == -1 || strPrice.indexOf(price) == -1){

        arr.goodsList.push({ 'id': id, 'goods_name': goods_name, 'goods_image': goods_image, 'num': num, 'price': price, 'active': true ,'label':label})
          
      }
      
     
      console.log('第二次添加到购物车')
    }
    
    return arr
  },
  /**
   * 转发分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.basicInfo.name,
      path: '/pages/goods_details/goods_details?id=' + this.data.goodsDetail.basicInfo.id + '&inviter_id=' + app.globalData.uid,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  /**
   * 选择商品规格
   */
  selectSpec: function (e) {
    var spec_id = e.currentTarget.dataset.id //规格id
    var spec_price = e.currentTarget.dataset.price //规格价格
    var category_id = e.currentTarget.dataset.category_id//规格类别
    var goodsDetail = this.data.goodsDetail; //商品详情
    var goods_price = goodsDetail.price
    var spec = this.data.spec//规格列表
    console.log(spec)
    for(var i in spec){
      if(spec[i].spec_id == spec_id){ 
            for(var j in spec){
              if (spec[j].spec_category_id == category_id) {
                spec[j].active = 0
              }
            }
        spec[i].active = 1;
        
      }
    }
    this.setData({spec:spec})
    var price = 0
    for(var t in spec){
      if(spec[t].active == 1){
        price += spec[t].spec_price
      }
    }
    this.setData({price:price+goods_price})
  },

  buliduBuyNowInfo : function (){
     var goods_name = this.data.goodsDetail.title//商品名称
     var goods_image = this.data.goodsDetail.image //图片
     var num = this.data.buyNumber//购买数量
     var spec = this.data.spec//规格
     var price = this.data.price == 0 ? this.data.goodsDetail.price:this.data.price//单价
     var label='';
     for(var i in spec){
       if(spec[i].active == 1){
         label += '"'+ spec[i].spec_name +'"'+ ','
       }
     }
    return [{ 'goods_name': goods_name, 'goods_image': goods_image, 'num': num, 'price': price,'label':label}]
  },
  /**
   * 购物车数量
   */
  cartShopNum: function(){
    var that = this;
    //购物车数据
    var shopCarInfo = wx.getStorageSync('shopCarInfo');
    if(shopCarInfo){
      var num = shopCarInfo.goodsList.length
      that.setData({ shopNum: num })
    }
    
  },
  phone:function(){
    wx.makePhoneCall({
      phoneNumber: '0755-33228631' //仅为示例，并非真实的电话号码
    })
  },


  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("white")
    context.fillRect(0, 0, 375, 667)
    // var path1 = that.data.touxiang;
    var path2 = "/image/haima.png";
    var path3 = "/image/zhanjiang.jpg";

    context.drawImage(path2, 80, 50, 220, 220);

    var name = that.data.name;
    //绘制产品名称
    context.setFontSize(24);
    context.setFillStyle('#333333');
    context.setTextAlign('center');
    context.fillText(name, 250, 330);
    context.stroke();

    context.drawImage(path3, 88, 400, 200, 200);

    //绘制头像
    //context.arc(186, 246, 50, 0, 2 * Math.PI) //画出圆
    // context.strokeStyle = "#ffe200";
    //context.strokeStyle = "#ffe200";
    //context.clip(); //裁剪上面的圆形
    //context.drawImage(path1, 136, 196, 100, 100); // 在刚刚裁剪的园上画图
    //价格
    var price1 = that.data.price1;
    context.setFontSize(24);
    context.setFillStyle('red');
    context.setTextAlign('center');
    context.fillText(price1, 110, 330);
    context.stroke();

    context.draw();
    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },
  //点击保存到相册
  baocun: function () {
    var that = this
    console.log("kgjgw")
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          }, fail: function (res) {
            console.log(11111)
          }
        })
      }
    })
  },
  //点击生成
  formSubmit: function (e) {
    var that = this;
    this.setData({
      maskHidden: false
    });
    wx.showToast({
      title: '海报生成中...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        maskHidden: true
      });
    }, 1000)
  },

})
